
//
//  LTNews.m
//  wangyiNews08
//
//  Created by 123 on 16/3/11.
//  Copyright © 2016年 Tsr. All rights reserved.
//

#import "LTNews.h"
#import "LTNetwrokTool.h"

// http://c.m.163.com/nc/article/headline/T1348647853363/0-140.html
@implementation LTNews

+ (instancetype)newsWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];
    
    [obj setValuesForKeysWithDictionary:dict];
    
    return obj;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

// @"article/headline/T1348647853363/0-140.html"
+ (void)newsWithURLString:(NSString *)URLString success:(void (^)(NSArray *))success error:(void (^)(NSError *))error {
   
    // 断言
    NSAssert(success != nil, @"必须传入block");
    
    [[LTNetwrokTool shareNetwrokTool] GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        // 获取最后一个key
        NSString *rootKey = responseObject.keyEnumerator.nextObject;
        // 更加key获得字典数据
        NSArray *newsArray = responseObject[rootKey];
        
        // 创建一个可变数组
        NSMutableArray *newsList = [NSMutableArray array];
        
        // 遍历字典数组
        [newsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 字典转模型
            LTNews *new = [LTNews newsWithDict:obj];
            
            // 添加到可变数组中
            [newsList addObject:new];
        }];
        
        // 成功回调
        success(newsList);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull er) {
        // 失败回调
        error(er);
    }];
}

@end
